import { defineStore } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export const useQuestionStore = defineStore('question', {
  state: () => ({
    questions: [],
    statistics: null,
    pendingRequests: new Map() // 存储正在进行的请求
  }),
  
  getters: {
    collectedQuestions: (state) => 
      state.questions.filter(q => q.isCollected === true),
    
    learnedQuestions: (state) => 
      state.questions.filter(q => q.isLearned === true)
  },
  
  actions: {
    async fetchQuestions() {
      try {
        const response = await axios.get('/api/questions')
        this.questions = response.data
        // 打印日志以便调试
        console.log('Fetched questions:', this.questions)
      } catch (error) {
        console.error('Failed to fetch questions:', error)
        throw error
      }
    },
    
    async addQuestion(question) {
      const response = await axios.post('/api/questions', { question })
      this.questions.unshift(response.data)
    },
    
    async toggleCollect(id) {
      await axios.post(`/api/questions/${id}/collect`)
      const question = this.questions.find(q => q.id === id)
      if (question) {
        question.isCollected = !question.isCollected
      }
    },
    
    async regenerateAnswer(id) {
      const question = this.questions.find(q => q.id === id)
      if (question) {
        question.regenerating = true
        
        // 创建可取消的请求
        const controller = new AbortController()
        this.pendingRequests.set(id, controller)
        
        try {
          const response = await axios.post(`/api/questions/${id}/regenerate`, null, {
            signal: controller.signal
          })
          const index = this.questions.findIndex(q => q.id === id)
          if (index !== -1) {
            this.questions[index].answer = response.data.answer
          }
        } catch (error) {
          if (error.name === 'AbortError') {
            // 请求被取消，不做任何处理
            return
          }
          throw error
        } finally {
          this.pendingRequests.delete(id)
          if (question) {
            question.regenerating = false
          }
        }
      }
    },
    
    cancelRegenerate(id) {
      const controller = this.pendingRequests.get(id)
      if (controller) {
        controller.abort()
        this.pendingRequests.delete(id)
      }
    },
    
    async toggleLearned(id) {
      try {
        const response = await axios.post(`/api/questions/${id}/learned`)
        // 更新本地状态
        const index = this.questions.findIndex(q => q.id === id)
        if (index !== -1) {
          this.questions[index] = response.data
        }
        // 打印日志
        console.log('Question learned status updated:', response.data)
        
        // 更新统计信息
        await this.getStatistics()
      } catch (error) {
        console.error('Failed to toggle learned status:', error)
        ElMessage.error('更新学习状态失败')
        throw error
      }
    },
    
    async getLearnedQuestions() {
      try {
        const response = await axios.get('/api/questions/learned')
        return response.data
      } catch (error) {
        console.error('Failed to get learned questions:', error)
        ElMessage.error('获取已学会的问题失败')
        throw error
      }
    },
    
    async getLearningList(topic) {
      const response = await axios.get('/api/questions/learning-list', {
        params: { topic }
      })
      return response.data
    },

    async searchQuestions(keyword) {
      const response = await axios.get('/api/questions/search', {
        params: { keyword }
      })
      this.questions = response.data
    },

    async getStatistics() {
      const response = await axios.get('/api/questions/statistics')
      this.statistics = response.data
      return response.data
    },

    async updateDifficulty(id, difficulty) {
      await axios.post(`/api/questions/${id}/difficulty`, null, {
        params: { difficulty }
      })
      const question = this.questions.find(q => q.id === id)
      if (question) {
        question.difficulty = difficulty
      }
    }
  }
}) 